import csv
from datetime import datetime
from config.config import  SLOW_API_PATH
import os


class ApiLogger(object):
    def __init__(self, filename=SLOW_API_PATH):
        self.filename = filename
        self.fieldnames = ["timestamp", "url", "method", "params", "data", "json", "response_time"]

        # 判断文件是否存在或者是否为空，文件为空的情况下写入表头
        if not os.path.exists(self.filename) or os.path.getsize(self.filename) == 0:
            with open(self.filename, 'a', newline='') as file:
                writer = csv.DictWriter(file, fieldnames=self.fieldnames)
                # 判断文件是否为空，文件为空的情况下写入表头
                writer.writeheader()


    def log_request(self, url, method, params, data, json, response_time):
        # 满接口定义，假设大于100ms

        if response_time >= 100:
            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            request_data = {
                "timestamp": timestamp,
                "url": url,
                "method": method,
                "params": params,
                "data": data,
                "json": json,
                "response_time": response_time
            }
            with open(self.filename, 'a', newline='') as file:
                writer = csv.DictWriter(file, fieldnames=self.fieldnames)
                writer.writerow(request_data)


